package com.itheima.reggie.web.controller;

import com.itheima.reggie.config.common.BaseContext;
import com.itheima.reggie.config.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;

    /**
     * 查询购物车
     * @return
     */
    @GetMapping("/list")
    public R<List<ShoppingCart>> list() {
        //日志
        log.debug("查询购物车：");

        //参数获取
        Long userId = BaseContext.getThreadLocal();

        //调用service
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(userId);

        //返回数据

        return R.success(shoppingCartList);
    }

    /**
     * 添加购物车
     *
     * @param shoppingCart 购物车项
     * @return 添加成功的购物车项
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        // 记录日志
        log.debug("添加到购物车，购物车详情是：[{}]", shoppingCart);

        //参数校验

        //调用service
        ShoppingCart sc = shoppingCartService.saveAndReturn(shoppingCart);

        //返回数据
        return R.success(sc);
    }
    /**
     * 减少购物车
     *
     * @param shoppingCart 购物车项
     * @return 减少成功的购物车项
     */
    @PostMapping("/sub")
    public R<ShoppingCart> sub(@RequestBody ShoppingCart shoppingCart){
        // 记录日志
        log.debug("购物车减少，购物车详情是：[{}]", shoppingCart);

        //参数校验

        //调用service
        ShoppingCart sc = shoppingCartService.deleteAndReturn(shoppingCart);

        //返回数据
        return R.success(sc);
    }


    /**
     * 清空购物车
     * @return
     */
    @DeleteMapping("/clean")
    public R clean(){
        //日志

        //获取登录用户id
        Long userId = BaseContext.getThreadLocal();

        //条件构建
        HashMap<String,Object> condition = new HashMap<>();
        condition.put("user_id", userId);

        //调用service
        boolean result = shoppingCartService.removeByMap(condition);

        if (result) {
            return R.success("购物车清空成功");
        }
        return R.error("购物车清空失败");

    }


}